package me.zhengjie.modules.xiao.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.modules.xiao.domain.CgCluetable;
import me.zhengjie.modules.xiao.domain.dto.*;
import me.zhengjie.modules.xiao.domain.vo.*;
import me.zhengjie.modules.xiao.mapper.CgCluetableMapper;
import me.zhengjie.modules.xiao.service.CgCluetableService;
import me.zhengjie.modules.xiao.service.CgNoticeService;
import me.zhengjie.utils.FileUtil;
import me.zhengjie.utils.PageResult;
import me.zhengjie.utils.PageUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
* @description 服务实现
* @author cg
* @date 2024-06-19
**/
@Slf4j
@Service
@RequiredArgsConstructor
public class CgCluetableServiceImpl extends ServiceImpl<CgCluetableMapper, CgCluetable> implements CgCluetableService {

    private final CgCluetableMapper cgCluetableMapper;
    private final UserService userService;
    private final CgNoticeService cgNoticeService;


    @Override
    public PageResult<CgCluetable> queryAll(CgCluetableQueryCriteria criteria, Page<Object> page){
        return PageUtil.toPage(cgCluetableMapper.findAll(criteria, page));
    }

    @Override
    public List<CgCluetable> queryAll(CgCluetableQueryCriteria criteria){
        return cgCluetableMapper.findAll(criteria);
    }

    @Override
    public Integer telCount(String phone){
        return cgCluetableMapper.telCount(phone);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(CgCluetable resources) {
        Integer count = cgCluetableMapper.telCount(resources.getCustomerTel());
        if(count>0){
            throw new RuntimeException("手机号已存在");
        }
        resources.setId(null);
        save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(CgCluetable resources) {
        CgCluetable cgCluetable = getById(resources.getId());
        if(resources.getDeptId()!=cgCluetable.getDeptId()){
            resources.setMessageStatus("1");
        }
        cgCluetable.copy(resources);
        saveOrUpdate(cgCluetable);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(List<Integer> ids) {
        removeBatchByIds(ids);
    }

    @Override
    public void download(List<CgCluetable> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (CgCluetable cgCluetable : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("线索来源", cgCluetable.getClueSource());
            map.put("客户名称", cgCluetable.getCustomerName());
            map.put("客户电话", cgCluetable.getCustomerTel());
            map.put("客户类型：客户/公海客户", cgCluetable.getCustomerFlag());
            map.put("客户状态：潜在/洽谈", cgCluetable.getCustomerStatus());
            map.put("注释", cgCluetable.getRemark());
            map.put("客户地址", cgCluetable.getCustomerAddress());
            map.put("部门ID", cgCluetable.getDeptId());
            map.put("业务公司", cgCluetable.getDeptName());
            map.put("创建者", cgCluetable.getCreateBy());
            map.put("更新者", cgCluetable.getUpdateBy());
            map.put("创建日期", cgCluetable.getCreateTime());
            map.put("更新时间", cgCluetable.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public List<CgHomeLineDTO> queryStrip(QueryStripVO queryVO) {
        Date date = queryVO.getTime();
        List<Date> thisTime = new ArrayList<>();
        if("1".equals(queryVO.getStatus())){
            thisTime.add(DateUtil.beginOfWeek(date));
            thisTime.add(DateUtil.endOfWeek(date));
        }else if("2".equals(queryVO.getStatus())){
            thisTime.add(DateUtil.beginOfMonth(date));
            thisTime.add(DateUtil.endOfMonth(date));
        } else if ("3".equals(queryVO.getStatus())) {
            thisTime.add(DateUtil.beginOfYear(date));
            thisTime.add(DateUtil.endOfYear(date));
        }
        queryVO.setThisTime(thisTime);
        return baseMapper.queryStrip(queryVO);
    }

    @Override
    public List<CgHomeLineDTO> queryLine(QueryLineVO queryVO) {
        List<Date> thisTime = new ArrayList<>();
        List<String> listDate = new ArrayList<>();
        if("1".equals(queryVO.getStatus())){
            thisTime.add(DateUtil.beginOfWeek(queryVO.getTime()));
            thisTime.add(DateUtil.endOfWeek(queryVO.getTime()));
            listDate.add("星期一");
            listDate.add("星期二");
            listDate.add("星期三");
            listDate.add("星期四");
            listDate.add("星期五");
            listDate.add("星期六");
            listDate.add("星期日");
        }else if("2".equals(queryVO.getStatus())){
            thisTime.add(DateUtil.beginOfMonth(queryVO.getTime()));
            thisTime.add(DateUtil.endOfMonth(queryVO.getTime()));
            //获取一月多少天
            int days = DateUtil.endOfMonth(queryVO.getTime()).dayOfMonth();
            for(int i=1;i<=days;i++){
                listDate.add(i+"");
            }
        } else if ("3".equals(queryVO.getStatus())) {
            thisTime.add(DateUtil.beginOfYear(queryVO.getTime()));
            thisTime.add(DateUtil.endOfYear(queryVO.getTime()));
            for(int i=1;i<=12;i++){
                if(i<10){
                   listDate.add("0"+i+"");
                }else{
                   listDate.add(i+"");
                }

            }
        }
        queryVO.setThisTime(thisTime);
        List<CgHomeLineDTO> list = baseMapper.queryLine(queryVO);
        String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        List<CgHomeLineDTO> listCgHomeLineDTO = new ArrayList<>();
        for(String str : listDate){
            CgHomeLineDTO entity= null;
            for(CgHomeLineDTO cgHomeLineDTO:list){
                if("1".equals(queryVO.getStatus())){
                    Date date = DateUtil.parse(cgHomeLineDTO.getName(),"yyyy-MM-dd");
                    String name = weekDays[DateUtil.dayOfWeek(date)-1];
                    if(str.equals(name)){
                        entity = new CgHomeLineDTO(str,cgHomeLineDTO.getTotal());
                    }
                }else if("2".equals(queryVO.getStatus())){
                    if(str.equals(cgHomeLineDTO.getName())){
                        entity = new CgHomeLineDTO(cgHomeLineDTO.getName(),cgHomeLineDTO.getTotal());
                    }
                }else if ("3".equals(queryVO.getStatus())) {
                    if(str.equals(cgHomeLineDTO.getName())){
                        entity = new CgHomeLineDTO(cgHomeLineDTO.getName(),cgHomeLineDTO.getTotal());
                    }
                }
            }
            if(entity ==null){
                entity = new CgHomeLineDTO(str,0L);
            }
            listCgHomeLineDTO.add(entity);
        }
        return listCgHomeLineDTO;
    }

    @Override
    public List<Map<String,Object>> queryReport(QueryReportVO queryVO) {
        List<Date> thisTime = new ArrayList<>();
        List<String> listDate = new ArrayList<>();
        if("1".equals(queryVO.getStatus())){
            thisTime.add(DateUtil.beginOfWeek(queryVO.getTime()));
            thisTime.add(DateUtil.endOfWeek(queryVO.getTime()));
            listDate.add("星期一");
            listDate.add("星期二");
            listDate.add("星期三");
            listDate.add("星期四");
            listDate.add("星期五");
            listDate.add("星期六");
            listDate.add("星期日");
        }else if("2".equals(queryVO.getStatus())){
            thisTime.add(DateUtil.beginOfMonth(queryVO.getTime()));
            thisTime.add(DateUtil.endOfMonth(queryVO.getTime()));
            //获取一月多少天
            int days = DateUtil.endOfMonth(queryVO.getTime()).dayOfMonth();
            for(int i=1;i<=days;i++){
                listDate.add(i+"");
            }
        } else if ("3".equals(queryVO.getStatus())) {
            thisTime.add(DateUtil.beginOfYear(queryVO.getTime()));
            thisTime.add(DateUtil.endOfYear(queryVO.getTime()));
            for(int i=1;i<=12;i++){
                if(i<10){
                   listDate.add("0"+i+"");
                }else{
                   listDate.add(i+"");
                }
            }
        }
        queryVO.setThisTime(thisTime);
        List<CgHomeReportDTO> list =  baseMapper.queryReport(queryVO);
        Map<String, List<CgHomeReportDTO>> mapList = list.stream().collect(Collectors.groupingBy(CgHomeReportDTO::getColumnType));
        List<Map<String,Object>> listMap = new ArrayList<>();
        String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        mapList.forEach((k,v)->{
            Map<String,Object> map = new HashMap<>();
            if("create_by".equals(queryVO.getColumnType())){
               User user = userService.findByName(k);
               map.put(queryVO.getColumnType(),user.getNickName());
            }else{
                map.put(queryVO.getColumnType(),k);
            }
            List<Map<String,Object>> dataList = new ArrayList<>();
            for(String str : listDate){
                CgHomeLineDTO entity= null;
                for(CgHomeReportDTO cgHomeReportDTO:v){
                    if("1".equals(queryVO.getStatus())){
                        Date date = DateUtil.parse(cgHomeReportDTO.getName(),"yyyy-MM-dd");
                        String name = weekDays[DateUtil.dayOfWeek(date)-1];
                        if(str.equals(name)){
                            entity = new CgHomeLineDTO(str,cgHomeReportDTO.getTotal());
                        }
                    }else if("2".equals(queryVO.getStatus())){
                        if(str.equals(cgHomeReportDTO.getName())){
                            entity = new CgHomeLineDTO(cgHomeReportDTO.getName(),cgHomeReportDTO.getTotal());
                        }
                    }else if ("3".equals(queryVO.getStatus())) {
                        if(str.equals(cgHomeReportDTO.getName())){
                            entity = new CgHomeLineDTO(cgHomeReportDTO.getName(),cgHomeReportDTO.getTotal());
                        }
                    }
                }
                if(entity ==null){
                    entity = new CgHomeLineDTO(str,0L);
                }
                Map<String,Object> dataMap = new HashMap<>();
                dataMap.put("time",entity.getName());
                dataMap.put("value",entity.getTotal());
                dataList.add(dataMap);
            }
            map.put("dataList",dataList);
            listMap.add(map);
        });
        return listMap;
    }

    @Override
    public PageResult<CustomerDTO> findCustomerAll(CustomerQueryCriteria criteria, Page<Object> page){
        return PageUtil.toPage(cgCluetableMapper.findCustomerAll(criteria, page));
    }

    @Override
    public List<ExcelClueDTO> excelClue(CgDateVo vo) {
        return cgCluetableMapper.excelClue(vo);
    }

    @Override
    public List<ExcelDesignDTO> excelDesign(CgDateVo vo) {
        return cgCluetableMapper.excelDesign(vo);
    }
    @Override
    public List<ExcelSignDTO> excelSign(CgDateVo vo) {
        return cgCluetableMapper.excelSign(vo);
    }
    @Override
    public List<ExcelBusDTO> excelBus(CgDateVo vo) {
        return cgCluetableMapper.excelBus(vo);
    }
    @Override
    public List<ExceDetailDTO> excelDetail(CgDateVo vo) {
        return cgCluetableMapper.excelDetail(vo);
    }

    @Override
    public List<ExcelTotalDTO> excelTotal(CgDateVo vo) {
        return cgCluetableMapper.excelTotal(vo);
    }

    @Override
    public void deleteByPhone(String phone) {
        LambdaQueryWrapper<CgCluetable> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CgCluetable::getCustomerTel, phone);
        cgCluetableMapper.delete(queryWrapper);
    }

    @Override
    public List<CgCusExcelDTO> queryExcel(CgCluetableQueryCriteria criteria){
        return cgCluetableMapper.queryExcel(criteria);
    }
}